#!/bin/bash
#mamibot_mqtt_v2

broker="192.192.192.1092"
port="1883"
topic_s="vacuum/status"
topic_i="vacuum/info"
topic_cmd="vacuum/command"
response_topic="vacuum/response"
client_id="mamibot"
username="username"
password="password"

data_file="data.txt"

send_message() {
    param1=$1
    param2=$2
    if [ "$param1" == "s" ]; then
        mosquitto_pub -h "$broker" -p "$port" -i "$client_id" -t "$topic_s" -u "$username" -P "$password" -m "$param2"
    elif [ "$param1" == "i" ]; then
        mosquitto_pub -h "$broker" -p "$port" -i "$client_id" -t "$topic_i" -u "$username" -P "$password" -m "$param2"
    fi
}

response_message() {
  lines=("$@")
  result_array=("${lines[@]}")
  mosquitto_pub -h "$broker" -p "$port" -i "$client_id" -t "$response_topic" -u "$username" -P "$password" -m "$(printf "%s\n" "${result_array[@]}")"
}

on_message() {
  message=$1

  if [ -n "$message" ]
  then
      result=$(eval "$message")
      mosquitto_pub -h "$broker" -p "$port" -i "$client_id" -t "$response_topic" -m "" -u "$username" -P "$password"
      response_message "${result}"
  fi
}
last_sent_time=0
send_interval=30

check_and_restart_mosquitto_sub() {
    if ! pgrep -x mosquitto_sub > /dev/null; then
        mosquitto_sub -h "$broker" -p "$port" -t "$topic_cmd" -u "$username" -P "$password" > "$data_file" &
    fi
}

mosquitto_sub -h "$broker" -p "$port" -t "$topic_cmd" -u "$username" -P "$password" > "$data_file" &

sub_pid=$!

while true; do
    current_time=$(date +%s)

    if (( current_time - last_sent_time >= send_interval )); then
        result_s=$(grep -A 11 "type=kBV_RobotState"  /mnt/UDISK/bvlog/bvrobot.log | tail -n 11)
        send_message "s" "$result_s"
        result_i=$(/root/a.out | jq 'del(.MapInfo.Data)')
        send_message "i" "$result_i"
        last_sent_time=$current_time
        check_and_restart_mosquitto_sub
    fi

    if [ -f "$data_file" ]; then
        while IFS= read -r -t 2 line; do
            if [ -n "$line" ]; then
                on_message "$line"
            else
                break
            fi
        done < "$data_file"
        > "$data_file"
    fi

    sleep 1
done

rm "$data_file"

kill $sub_pid
